package br.com.canvasForAll.model.generic.dao;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

import br.com.canvasForAll.model.generic.repository.GenericCrudRepository;

@Stateless
public abstract class GenericCrudDao<T> implements GenericCrudRepository<T> {

		private final String PERSISTENCE_UNIT = "canvasForAll-ics";
		
		@PersistenceContext(unitName=PERSISTENCE_UNIT)
		protected EntityManager em;
		
		private Class<T> entity;
		
		public GenericCrudDao(Class<T> entity){
			this.entity = entity;
		}
		
		public void criar(T entity) throws Exception{
			em.persist(entity);
		}
		
		public void deletar(T entity) throws Exception{
			T entityRemoved = em.merge(entity);
			em.remove(entityRemoved);
		}
		
		public T atualizar(T entity) throws Exception{
			return em.merge(entity);
		}
		
		public T obterPorId(Long entityId) throws Exception{
			return em.find(entity, entityId);
		}
		
		@SuppressWarnings({ "unchecked", "rawtypes" })
		public List<T> obterTodos() throws Exception{
			CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
			cq.select(cq.from(entity));
			return (List<T>) em.createQuery(cq).getResultList();
		}
		
		@SuppressWarnings("unchecked")
		public List<T> obterPorExemplo(String namedQuery, Map<String, Object> parameters) throws Exception{
			List<T> result = null;

			try{
				Query query = em.createNamedQuery(namedQuery);
				
				if(parameters != null && !parameters.isEmpty()){
					for(Entry<String, Object> entry : parameters.entrySet()){
						query.setParameter(entry.getKey(), entry.getValue());
					}
				}
				
				result = query.getResultList();
				
			} catch (Exception e) {
				System.out.println("Erro ao tentar pesquisar.");
				e.printStackTrace();
			}

			return result;
		}
	
}